#include <engine.h>

GGame::GGame()
{
    m_pWindow = NULL;
}

GGame::~GGame()
{
}

void GGame::SetGameWindow(GWindow* pWindow)
{
	m_pWindow = pWindow;
}

GWindow* GGame::GetWindow()
{
    return m_pWindow;
}

GObjects* GGame::GetAllObjects()
{
    return &m_go_all;
}

GAnimates* GGame::GetAnimateObjects()
{
    return &m_go_animate;
}

void GGame::AddObject(GObject* pObject, int x, int y)
{
    Q_ASSERT(pObject);

    pObject->setPos(x,y);
    GetWindow()->AddObject(pObject);
    m_go_all.push_back(pObject);
}

void GGame::AddAnimate(GAnimate* pAni)
{
    Q_ASSERT(pAni);

    m_go_animate.push_back(pAni);
}

GObject* GGame::FindObject(QString name)
{
    GObjects_itor itor;
    for(itor = m_go_all.begin(); itor != m_go_all.end(); itor++)
    {
        GObject* pGo = *itor;
        if(pGo && (name.compare(pGo->GetName(), Qt::CaseSensitive) == 0))
            return pGo;
    }

    return NULL;
}

bool GGame::GameInitialize()
{
    return false;
}

void GGame::GameStart()
{
}

void GGame::GameEnd()
{
}

void GGame::GarbageCollect()
{
	GObjects_itor it = m_go_all.begin();
    GObjects_itor end = m_go_all.end();
    while(it != end)
    {
        GObject *pObject = *it;
        Q_ASSERT(pObject);

		if(pObject->GetGarbage())
		{
			it = m_go_all.erase(it);
			delete pObject;
			qDebug() << "garbage collect";
			continue;
		}
		
		++it;
    }
}

bool GGame::event(QEvent* event)
{
	GEvent* pEvent = static_cast<GEvent*>(event);
	if(pEvent->type() == GEvent::Evt_Garbage) 
	{
		GarbageCollect();
	}
	
    return QObject::event(event);
}